<?php

App::uses('AppController', 'Controller');

/**
 * Events Controller
 *
 * @property Event $Event
 * @property Gevent $Gevent
 */
class EventsController extends AppController {

    public $helpers = array('Form', 'GdgUpload.Upload');
//    public $cacheAction = array(
//        'view' => "1 hour",
//        'index'  => "1 hour"
//    );
    public $paginate = array(
        'fields' => array('Event.id', 'Event.name', 'Event.startdate', 'Event.accepting', 'Event.active', 'Event.chapter_id', 'Event.user_id', 'Event.registered','Chapter.name','User.name'),
        'contain' => array('Chapter','User'),
        'limit' => 25,
        'order' => array(
            'Event.id' => 'desc'
        )
    );
    
    public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->deny(array('admin_index', 'admin_view', 'admin_add', 'admin_edit', 'admin_delete','admin_registered'));
    }

    /**
     * index method
     *
     * @return void
     */
    public function index() {
        $conditions = array('Event.active' => 1, 'Event.startdate >' => date('Y-m-d'));
        $isPastEventsView = false;
        if(!empty($this->request->params['named'])){
            if(!empty($this->request->params['named']['since'])){
                $isPastEventsView = true;
                if($this->request->params['named']['since'] == 'now'){
                    $this->request->params['named']['since'] = date('Y-m-d');
                }
                $conditions = array('Event.active' => 1, 'Event.startdate <=' => $this->request->params['named']['since']);
            }
        }
        
        $this->set('futureEvents', !$isPastEventsView);
        
        $this->helpers[] = 'Timepl';
        $data = $this->Event->find('all', array(
            'conditions'    => $conditions,
            'fields'        => array('Event.name', 'Event.startdate', 'Event.accepting', 'Event.slug', 'Event.chapter_id', 'Chapter.name', 'Chapter.url', 'Chapter.slug', 'Chapter.image'),
            'order'         => 'Event.startdate DESC',
            'limit'         => 50
        ));
        $this->set('events', $data);
        
        if(!$isPastEventsView){
            //
            // Find Google plus events
            //
            $gplusEvents = $this->getGplusEvents();
            $this->set('gplusEvents', $gplusEvents);
        }
        
        $this->response->cache('-1 minute', '+12 hours');
        $this->cacheAction = '+12 hours';
    }
    
    private function getGplusEvents(){
        $this->loadModel('Gevent');
        $data = $this->Gevent->find('all', array(
            'conditions'    => array('Gevent.active' => 1),
            'order'         => 'Gevent.created DESC'
        ));
        return $data;
    }


    
    
    
    
    /**
     * view method
     *
     * @param string $id
     * @return void
     */
    public function view($slug = null) {
        $this->helpers[] = 'Timepl';
        $this->helpers[] = 'Text';
        App::uses('Sanitize', 'Utility');
        if (!$slug) {
            throw new NotFoundException(__('Event not found'));
        }
        $this->Event->unbindModel(
            array('belongsTo'=>array('User'))
        );
        $this->Event->recursive = 0;
        $event = $this->Event->find('first', array(
            'conditions' => array('Event.slug' => $slug),
            'contain'   => array(
                'Place' => array('Address'), 
                'Chapter'
            )
        ));
        if (!$event) {
            throw new NotFoundException(__('Event not found'));
        }
        
        $this->set('event', $event);
        $this->response->cache('-1 minute', '+12 hours');
        $this->cacheAction = '+12 hours';
    }
    
    /**
     * Register active user to event. 
     * It is only available for ajax calls via /events/register/ID.json url.
     * @param $id  event ID
     */
    public function register($id=null){
        if(!$id) {
            throw new NotFoundException(__('Event not found (no id)'));
        }
        if($this->Auth->user() == null){
            throw new ForbiddenException(__('You must login to register to event.'));
        }
        $this->Event->id = $id;
        if(!$this->Event->exists()){
            throw new NotFoundException(__('Event not found (not exists)'));
        }
        
        $this->Event->recursive = 0;
        $event = $this->Event->find('first', array(
            'conditions' => array('Event.id' => $id),
            'contain'   => array(
                'Place' => array('Address'), 
                'Chapter'
            )
        ));
        
        if($event['Event']['active'] !== true){
            throw new NotFoundException(__('Event not found (not active)'));
        }
        
        if($event['Event']['accepting'] !== true){
            $this->set('result', array('error'=>'Rejestracja na spotkanie nie jest aktywna'));
            return;
        }
        $userId = $this->Auth->user('id');
        $fieldsData = array(
            'event_id'  => $id,
            'user_id'   => $userId
        );
        $this->Event->Registration->deleteAll($fieldsData);
        $data = array('Registration' => $fieldsData);
        
        $limit = $event['Event']['limit'];
        $onhold = false;
        if($limit){
            $currentCount = $this->Event->Registration->find('count',array(
                'conditions' => array('Registration.event_id' => $id, 'onhold' => 0)
            ));
            if($currentCount > $limit){
                $onhold = true;
            }
        }
        if($onhold){
            $data['Registration']['onhold'] = 1;
        }
        
        
        if($this->Event->Registration->save($data)){
            $this->set('result',array('result'=>true,'onhold'=>$onhold,'form' => $event['Event']['form'] == null ? null : $event['Event']['form'], 'uid'=>$userId));
            
            try{
                if($onhold){
                    $this->sendRegistrationMail($event, true);
                } else {
                    $this->sendRegistrationMail($event);
                }
            }catch(Exception $e){
                $this->log($e->getMessage() . $e->getTraceAsString());
            }
            
        } else {
            $this->set('result',array('error'=>'Wystąpił błąd zapisu w bazie danych.'));
        }
    }
    
    private function sendRegistrationMail($event, $onHold = false){
        App::uses('CakeEmail', 'Network/Email');
        
        $tpl = 'event_register';
        if($onHold){
            $tpl .= '_hold';
        }
        
        $user = $this->Auth->user();
        $email = new CakeEmail();
        
        $email->template($tpl)
            ->emailFormat('text')
            ->from(array('noreply@gdgs.pl' => 'Google Developers Groups - Polska'))
            ->to($user['email'])
            ->subject('[GDG] Potwierdzenie rejestracji na spotkanie')
            ->viewVars(array('event' => $event))
            ->send();
    }
    
    
    
    public function unregister($id=null){
        if(!$id) {
            throw new NotFoundException(__('Event not found (no id)'));
        }
        if($this->Auth->user() == null){
            throw new ForbiddenException(__('You must login to register to event.'));
        }
        $this->Event->id = $id;
        if(!$this->Event->exists()){
            throw new NotFoundException(__('Event not found (not exists)'));
        }
        $userId = $this->Auth->user('id');
        $fieldsData = array(
            'event_id'  => $id,
            'user_id'   => $userId
        );
        $this->Event->Registration->deleteAll($fieldsData);
        
        //check if some user is waiting to register
        $waiting = $this->Event->Registration->find('first',array(
            'conditions' => array('Registration.event_id' => $id, 'onhold' => 1)
        ));
        if($waiting){
            
        }
        
        $this->set('result',array('result'=>true));
    }
    /**
     *  Check state for given events list if user is registered for event 
     */
    public function state(){
        if($this->Auth->user() == null){
            throw new ForbiddenException(__('You are not logged in.'));
        }
        if(empty($this->request->data['Registration']) || count($this->request->data['Registration'])==0){
            $this->set('result',array('registered'=>array()));
            return;
        }
        $events = array();
        foreach($this->request->data['Registration']['id'] as $ev){
            $events[] = $ev;
        }
        
        $userId = $this->Auth->user('id');
        $data = $this->Event->Registration->find('all', array(
            'fields' => array('Registration.event_id'),
            'conditions'    => array(
                'Registration.event_id' => $events,
                'Registration.user_id' => $userId
             )
        ));
        $result = array();
        if($data){
            foreach($data as $registration){
                $result[] = (int)$registration['Registration']['event_id'];
            }
        }
        $this->set('result',array('registered'=>$result));
    }
    
    
    
    public function pastevents($page=1, $chapter=null){
        if(is_nan($page)){
            $page = 1;
        } else {
            $page = intval($page);
        }
        $conditions = array('Event.active' => 1, 'Event.startdate <=' => date('Y-m-d'));
        if($chapter != null){
            if(is_nan($chapter)){
                $chapter = null;
            } else {
                $chapter = intval($chapter);
                $conditions['Event.chapter_id'] = $chapter;
            }
        }
        $limit = 25;
        $this->Event->recursive = 0;
        $this->helpers[] = 'Timepl';
        $data = $this->Event->find('all', array(
            'conditions' => $conditions,
            'fields' => array('Event.name', 'Event.startdate', 'Event.slug', 'Event.chapter_id', 'Chapter.name', 'Chapter.url', 'Chapter.slug', 'Chapter.image'),
            'order' => 'Event.startdate DESC',
            'page'  => $page,
            'limit' => $limit
        ));
        if(count($data)<$limit){
            $this->set('hasMore', false);
        } else {
            $this->set('hasMore', true);
        }
        $this->set('events', $data);
        $this->response->cache('-1 minute', '+12 hours');
        $this->cacheAction = '+12 hours';
    }
    

    /**
     * admin_index method
     *
     * @return void
     */
    public function admin_index() {
        $this->Event->recursive = 0;
        $this->helpers[] = 'Text';
        
        $this->set('events', $this->paginate());
    }

    /**
     * admin_view method
     *
     * @param string $id
     * @return void
     */
    public function admin_view($id = null) {
        $this->Event->id = $id;
        if (!$this->Event->exists()) {
            throw new NotFoundException(__('Invalid event'));
        }
        $this->set('event', $this->Event->read(null, $id));
    }

    /**
     * admin_add method
     *
     * @return void
     */
    public function admin_add() {
        if ($this->request->is('post')) {
            $this->Event->create();
            if(!empty($this->request->data['Event']['place_id'])){
                unset($this->request->data['Address']);
                unset($this->request->data['Place']);
            } else {
                $this->Event->Place->Address->create();
                if(!empty($this->request->data['Address']['postal'])){
                    $this->Event->Place->Address->save($this->request->data['Address']);
                    unset($this->request->data['Address']);
                    $this->request->data['Place']['limit'] = $this->request->data['Event']['limit'];
                    $this->request->data['Place']['address_id'] = $this->Event->Place->Address->id;
                } else {
                    if(empty($this->request->data['Place']['name'])){
                        unset($this->request->data['Place']);
                    }
                }
            }
            
            if ($this->Event->saveAll($this->request->data)) {
                $this->Session->setFlash(__('The event has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The event could not be saved. Please, try again.'));
            }
        }
        $chapters = $this->Event->Chapter->find('list');
        $this->set(compact('chapters'));
    }

    /**
     * admin_edit method
     *
     * @param string $id
     * @return void
     */
    public function admin_edit($id = null) {
        $this->Event->id = $id;
        if (!$this->Event->exists()) {
            throw new NotFoundException(__('Invalid event'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            if ($this->Event->save($this->request->data)) {
                $this->Session->setFlash(__('The event has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The event could not be saved. Please, try again.'));
            }
        } else {
            $this->request->data = $this->Event->read(null, $id);
        }
        $places = $this->Event->Place->find('list');
        $chapters = $this->Event->Chapter->find('list');
        $users = $this->Event->User->find('list');
        $this->set(compact('places', 'chapters', 'users'));
    }

    /**
     * admin_delete method
     *
     * @param string $id
     * @return void
     */
    public function admin_delete($id = null) {
        if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
        $this->Event->id = $id;
        if (!$this->Event->exists()) {
            throw new NotFoundException(__('Invalid event'));
        }
        if ($this->Event->delete()) {
            $this->Session->setFlash(__('Event deleted'));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Event was not deleted'));
        $this->redirect(array('action' => 'index'));
    }
    
    public function admin_registered($id=null) {
        $this->Event->id = $id;
        if (!$this->Event->exists()) {
            throw new NotFoundException(__('Invalid event'));
        }
        $this->Event->Registration->bindModel(array(
            'belongsTo' => array('User' => array('fields'=>array('name','email','google','facebook')))
        ));
        $this->Event->Registration->recursive = 1;
        $this->set('event', $this->Event->Registration->findAllByEventId($id)); 
    }
}
